package com.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.dao.ISchoolDao;
import com.entity.School;
import com.tools.Page;

/**
 * 学校的dao
 * @author Administrator
 *
 */
public class SchoolDao extends BaseDao implements ISchoolDao{
	public SchoolDao(int type) {
		super(type);
	}

	/* (non-Javadoc)
	 * @see com.dao.ISchoolDao#save(com.entity.School)
	 */
	@Override
	public boolean save(School school) throws SQLException{
		String sql="insert into school values(?,?,?)";
		ps=con.prepareStatement(sql);
		
		ps.setString(1, school.getId());
		ps.setString(2, school.getName());
		ps.setString(3, school.getInfo());
		
		int num = ps.executeUpdate();
		
		if(num==1){
			return true;
		}
		else{
			return false;
		}
	}
	
	/* (non-Javadoc)
	 * @see com.dao.ISchoolDao#update(com.entity.School)
	 */
	@Override
	public boolean update(School school) throws SQLException{
		String sql="update school set name=?,info=? where id=?";
		ps=con.prepareStatement(sql);
		
		ps.setString(1, school.getName());
		ps.setString(2, school.getInfo());
		ps.setString(3, school.getId());
		int num = ps.executeUpdate();
		
		if(num==1){
			return true;
		}
		else{
			return false;
		}
	}
	
	/* (non-Javadoc)
	 * @see com.dao.ISchoolDao#findById(java.lang.String)
	 */
	@Override
	public School findById(String id) throws SQLException{
		String sql="select * from school where id=?";
		ps=con.prepareStatement(sql);
		
		ps.setString(1, id);
		
		rs=ps.executeQuery();
		
		if(rs.next()){
			School school=new School();
			school.setId(rs.getString("id"));
			school.setName(rs.getString("name"));
			school.setInfo(rs.getString("info"));
			return school;
		}
		return null;
	}
	
	/* (non-Javadoc)
	 * @see com.dao.ISchoolDao#getList(com.tools.Page)
	 */
	@Override
	public List<School> getList(Page page) throws SQLException{
		String sql="select * from school order by name limit ?,?";
		ps=con.prepareStatement(sql);
		
		ps.setLong(1, page.getIndex());
		ps.setLong(2, page.getSize());
		
		rs=ps.executeQuery();
		
		List<School> list=new ArrayList<>();
		
		while(rs.next()){
			School school=new School();
			school.setId(rs.getString("id"));
			school.setName(rs.getString("name"));
			school.setInfo(rs.getString("info"));
			list.add(school);
		}
		return list;
	}
	
	/* (non-Javadoc)
	 * @see com.dao.ISchoolDao#count()
	 */
	@Override
	public long count() throws SQLException{
		String sql="select count(*) from school";
		ps=con.prepareStatement(sql);
		
		
		rs=ps.executeQuery();
		
		
		if(rs.next()){
			return rs.getLong(1);
		}
		return 0;
	}
}
